import { createRouter, createWebHistory } from 'vue-router';
import Home from '@/views/Home.vue';
import Profile from '@/views/Profile.vue';
import Level from '@/views/Level.vue';
import Login from '@/views/Login.vue';
import Register from '../views/Register.vue';
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/profile',
    name: 'Profile',
    component: Profile,
    meta:{requiresAuth: true}
  },
  {
    path: '/level/:id',
    name: 'Level',
    component: Level,
    meta:{requiresAuth: true}
  },
  {
    path: '/login',
    name: 'Login', 
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});
// 导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  if (to.matched.some(record => record.meta.requiresAuth) && !token) {
    next('/login'); // 未登录时跳转到登录页面
  } else {
    next(); // 已登录或访问无需登录的页面，继续导航
  }
});
export default router;